package org.suyafei.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.suyafei.controller.request.ShortLinkAddRequest;
import org.suyafei.controller.request.ShortLinkDelRequest;
import org.suyafei.controller.request.ShortLinkPageRequest;
import org.suyafei.controller.request.ShortLinkUpdateRequest;
import org.suyafei.service.ShortLinkService;
import org.suyafei.utils.JsonData;
import org.suyafei.vo.ShortLinkVO;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 宿某人
 * @Date: 2021/12/17/3:34 下午
 * @Description:
 */
@Slf4j
@RequestMapping("/api/link/v1")
@RestController
public class ShortLinkController {

    @Autowired
    private ShortLinkService shortLinkService;

    @Value("${rpc.token}")
    private String rpcToken;


    /**
     * rpc 调用检查锻炼是否存在
     * @param shortLinkCode
     * @param request
     * @return
     */
    @GetMapping("check")
    public JsonData check(@RequestParam ("shortLinkCode") String shortLinkCode, HttpServletRequest request) {
        String token = request.getHeader("rpc-token");
        if (rpcToken.equalsIgnoreCase(token)) {
            ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);
            return shortLinkVO == null ? JsonData.buildError("短链不存在") : JsonData.buildSuccess();
        }else {
            return JsonData.buildError("非法访问");
        }



    }
    @PostMapping("add")
    public JsonData createShortLink(@RequestBody ShortLinkAddRequest request) {
        JsonData jsonData = shortLinkService.createShortLink(request);
        return jsonData;
    }

    @PostMapping("page")
    public JsonData pageShortLinKByGroupId(@RequestBody ShortLinkPageRequest shortLinkPageRequest) {
        Map<String, Object> result = shortLinkService.pageShortLinKByGroupId(shortLinkPageRequest);
        return JsonData.buildSuccess(result);
    }

    @PostMapping("del")
    public JsonData del(@RequestBody ShortLinkDelRequest shortLinkDelRequest) {
        JsonData jsonData = shortLinkService.del(shortLinkDelRequest);
        return jsonData;
    }

    @PostMapping("update")
    public JsonData del(@RequestBody ShortLinkUpdateRequest shortLinkUpdateRequest) {
        JsonData jsonData = shortLinkService.update(shortLinkUpdateRequest);
        return jsonData;
    }



}
